package com.example.alarmcontrolpanel;

import java.util.Calendar;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class Main extends Activity
{
	public static Context CONTEXT_APP;
	public static PreferenceUpdate currentCounter;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);
		String[] month={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};		
		Calendar cCal= Calendar.getInstance();
		int mm= cCal.get(Calendar.MONTH);
		int dd= cCal.get(Calendar.DATE);
		int yy= cCal.get(Calendar.YEAR);
		CONTEXT_APP = getApplicationContext();
		TextView dispDate= (TextView) findViewById(R.id.showDate);
		String date = Integer.toString(dd) + "/" + month[mm] + "/" + Integer.toString(yy);
		dispDate.setText(date);
		SharedPreferences sharedPrefCounter = CONTEXT_APP.getSharedPreferences("com.Counter", 0);
		int count=sharedPrefCounter.getInt("Count", 0);
		listAllAlarms(count);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main_activity, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
	    // Handle item selection
	    switch (item.getItemId())
	    {
	        case R.id.delete:
	        	//delete function goes here
	            return true;
	        case R.id.createTask:
	        	Intent createAlarm = new Intent(this,AlarmCreator.class);
	    		startActivity(createAlarm);
	        	//create task function goes here
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	public void onResume()
	{
		super.onResume();
		TableRow main_body = (TableRow) findViewById(R.id.main_header);
		ScrollView body = (ScrollView) findViewById(R.id.ScrollBody);
		body.removeAllViews();
		SharedPreferences sharedPrefCounter = CONTEXT_APP.getSharedPreferences("com.Counter", 0);
		int count=sharedPrefCounter.getInt("Count", 0);
		TextView tv = new TextView(this);
		main_body.removeView((TextView) findViewById(1111));
		tv.setId(1111);
		tv.setVisibility(1);
		tv.setText("Count: "+Integer.toString(count));
		main_body.addView(tv);
		listAllAlarms(count);
	}
	private void listAllAlarms(int count)
	{
		ScrollView body = (ScrollView) findViewById(R.id.ScrollBody);
		TableLayout TBody = new TableLayout(CONTEXT_APP);
		TableLayout.LayoutParams TbodyLayout = new TableLayout.LayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
		TBody.setLayoutParams(TbodyLayout);
		TBody.setId(111);
		/**
		 * This creates the basic structure for the list of the alarms.
		 * */
		if(count==0)
		{
			/**
			 * This part of code runs if there is no alarms set,
			 * because on set of even the first alarm the counter value will increase to 1.
			 * 
			 * So simply print there are no alarms set
			 * */
			TextView textDisp = new TextView(CONTEXT_APP);
			textDisp.setText("No Alarms Available");
			textDisp.setVisibility(1);
			TBody.addView(textDisp);
		}
		else
		{
			@SuppressWarnings("unused")
			int alarm_id = 0;
			int[] repeatDay = new int[7];
			int repeatType = 0;
			String desc = "";
			Calendar Cal = Calendar.getInstance();
			/**
			 * Now here lies the biggest problem. that is of listing all the alarms.
			 * We already have the number of number of Alarms Saved in the memory. That is stored in count.
			 * For Displaying the Alarms we would require table rows. So we will take it as array
			 * */
			TableRow[] tr = new TableRow[count];
			CheckBox[] checkAlarm = new CheckBox[count];
			SharedPreferences sharedAlarmList = CONTEXT_APP.getSharedPreferences("com.AlarmList", 0);
			for(int j=0;j<count;j++) //this would itterate number of times number of alarms are saved.
			{
				String newStr=sharedAlarmList.getString("Key"+Integer.toString(j), null);
				
				/**
				 * The upper codes find the alarm list by the list with each itteration.
				 * */
				String calcStr;
				if(newStr!=null) /** This checks to confirm that there is something in the string */
				{
					for(int i=0;i<5;i++) /** From here the code goes for Sting manipulation */
					{
						if(i<4)
						{
							calcStr = newStr.substring(0,newStr.indexOf('`'));
							newStr = newStr.substring(newStr.indexOf('`')+1);
						}
						else
						{
							calcStr = newStr;
						}
						switch(i)
						{
							case 0://Alarm Id
							{
								alarm_id  = Integer.parseInt(calcStr);
								break;
							}
							case 1://Description
							{
								desc  = calcStr;
								break;
							}
							case 2://Repeat Day
							{
								for(int m=0;m<7;m++)
								{
									repeatDay[m]=Integer.parseInt(Character.toString(calcStr.charAt(m)));
								}
								break;
							}
							case 3://repeat Type
							{
								repeatType = Integer.parseInt(calcStr);
								break;
							}
							case 4://Calendar
							{
								Cal= Calendar.getInstance();
								Cal.setTimeInMillis(Long.parseLong(calcStr));
								break;
							}
						}
					}
				}
				/**
				 * Now to display each alarm we have to check the type of the alarm. 
				 * */
				String str = new String();
				if(Cal.get(Calendar.HOUR)==0) 
				{
					/**
					 * The Calendar Class returns 0 when hour is set to 12
					 * To show the user hour as 12 we need this if and else statements
					 * **/
					str = Integer.toString(12)+":"+Integer.toString(Cal.get(Calendar.MINUTE));
				}
				else
				{
					str = Integer.toString(Cal.get(Calendar.HOUR))+":"+Integer.toString(Cal.get(Calendar.MINUTE));	
				}
				
				if(Cal.get(Calendar.AM_PM)==0)
				{
					str=str+"AM\n";
					/**
					 * As we need to know the time period as AM and PM for the time so it
					 * is necessary for us to know the time in AM and PM.
					 * So this code tells us about it.
					 * 
					 * */
				}
				else
				{
					str=str+"PM\n";
				}
				
				switch(repeatType)
				{
					case 0: /**  Repeat Days   */
					{
						String[] days = {"Su","Mo","Tu","We","Th","Fr","Sa"};
						String showDay = new String();
						for(int m=0;m<7;m++)
						{
							if(repeatDay[m]==1)
							{
								showDay += days[m]+ " ";
							}
						}
						str=str+showDay+"\n"+desc;
						break;
					}
					case 1: /**  Repeat none Play on Date  */
					{
						String[] months = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
						str=str+Integer.toString(Cal.get(Calendar.DATE))+"/"+months[Cal.get(Calendar.MONTH)]+"/"+Integer.toString(Cal.get(Calendar.YEAR))+"\n"+desc;
						break;
					}
					case 2: /**  Repeat Monthly  */
					{
						str=str+"Repeats Monthly\n"+desc;
						break;
					}
					case 3: /**  Repeat Yearly   */
					{
						str=str+"Repeats Yearly\n"+desc;
						break;
					}
				}
				//here in the above code, I just need to correct the Str.
				checkAlarm[j] = new CheckBox(CONTEXT_APP);
				checkAlarm[j].setText(str);
				tr[j] = new TableRow(CONTEXT_APP);
				tr[j].addView(checkAlarm[j]);
				LayoutParams layout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
				tr[j].setLayoutParams(layout);
				if(j%2==0)
				{
					tr[j].setBackgroundColor(Color.DKGRAY);
				}
				else
				{
					tr[j].setBackgroundColor(Color.GRAY);
				}
				TBody.addView(tr[j]);
			}
		}
		body.addView(TBody);
	}
}
